/*
 * @Author: xuhongling
 * @Date:   2021-12-27 14:36:43
 * @Last Modified by:   xuhongling
 * @Last Modified time: 2024-01-29 09:22:16
 */
import type { Map } from 'ol';
import { Vector as VectorLayer } from 'ol/layer';
import VectorSource from 'ol/source/Vector';
import { Style, Icon } from 'ol/style';
import { Point } from 'ol/geom';
import Feature from 'ol/Feature';
import useRemoveLayer from './useRemoveLayer';

interface PointInfo {
  lgtd: number;
  lttd: number;
  icon: string;
  iconScale?: number;
  zoom?: number;
}

export function useAddTipsPoint(globalMap: Map) {
  // 地图添加站点
  function addTipsPoint(pointInfo: PointInfo) {
    const lgtd = Number(pointInfo.lgtd);
    const lttd = Number(pointInfo.lttd);
    globalMap.getView().animate({
      center: [lgtd, lttd], //平移到点[-74, 38]，有缓动效果
      duration: 1000, //动画时间
      zoom: pointInfo.zoom ? pointInfo.zoom : 13, //设置地图视图中心点
    });

    // 设置站点样式
    function createStyle() {
      return new Style({
        image: new Icon({
          anchor: [0.5, 0.5],
          crossOrigin: 'anonymous',
          src: pointInfo.icon,
          scale: pointInfo.iconScale ? pointInfo.iconScale : 1,
          offset: [0, 0],
        }),
      });
    }

    const iconFeature = new Feature(new Point([lgtd, lttd]));
    iconFeature.set('style', createStyle());

    const vectorLayer = new VectorLayer({
      style: function (feature) {
        return feature.get('style');
      },
      source: new VectorSource({ features: [iconFeature] }),
      zIndex: 10,
    });
    vectorLayer.set('layerName', `TipsPointIconLayer`);
    vectorLayer.set('className', `vectorLayerLocationIcon`);
    globalMap.addLayer(vectorLayer);
  }


  function addTipsPointList(pointInfo: PointInfo) {
    const lgtd = Number(pointInfo.lgtd);
    const lttd = Number(pointInfo.lttd);


    // 设置站点样式
    function createStyle() {
      return new Style({
        image: new Icon({
          anchor: [0.5, 0.5],
          crossOrigin: 'anonymous',
          src: pointInfo.icon,
          scale: pointInfo.iconScale ? pointInfo.iconScale : 1,
          offset: [0, 0],
        }),
      });
    }

    const iconFeature = new Feature(new Point([lgtd, lttd]));
    iconFeature.set('style', createStyle());

    const vectorLayer = new VectorLayer({
      style: function (feature) {
        return feature.get('style');
      },
      source: new VectorSource({ features: [iconFeature] }),
      zIndex: 10,
    });
    vectorLayer.set('layerName', `TipsPointIconLayer`);
    vectorLayer.set('className', `vectorLayerLocationIcon`);
    globalMap.addLayer(vectorLayer);
  }

  // 删除图层
  function removeLayer() {
    useRemoveLayer(globalMap, `TipsPointIconLayer`);
  }

  return {
    addTipsPoint,
    removeLayer,
    addTipsPointList,
  };
}
